package com.fs.ibox_h.dao.impl;

import com.fs.ibox_h.dao.OrdersDao;
import com.fs.ibox_h.pojo.Orders;
import com.fs.ibox_h.util.JDBCUtil;
import com.fs.ibox_h.vo.Condition;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrdersDaoImpl implements OrdersDao {
    @Override
    public List<Orders> queryAll() {
        String sql = "SELECT * FROM tb_orders";
        List<Orders> orders = JDBCUtil.executeQuery(sql, Orders.class);
        System.out.printf("%s\n", orders);

        return orders;
    }
    public int count(Condition condition) {
        StringBuffer sql = new StringBuffer("SELECT COUNT(1) FROM tb_orders WHERE 1=1");
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        ArrayList<Object> list = new ArrayList<>();
        // 拼接条件
        setValue(sql,condition,list);
        try {
            conn= JDBCUtil.getConnection();
            psmt = conn.prepareStatement(sql.toString());
            // 给？赋值
            for (int i = 0; i <list.size() ; i++) {
                psmt.setObject(i+1,list.get(i));
            }
            rs = psmt.executeQuery();
            rs.next();
            return rs.getInt(1);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.close(rs,psmt,conn);
        }
        return 0;
    }

    @Override
    public List<Orders> selectByCondition(int currentPage, int pageSize, Condition condition) {
        StringBuffer sql = new StringBuffer("SELECT * FROM tb_orders WHERE 1 = 1");
        ArrayList<Object> list = new ArrayList<>();
        setValue(sql, condition, list);
        sql.append(" LIMIT ?,?");
        list.add((currentPage-1)*pageSize);
        list.add(pageSize);
        return JDBCUtil.executeQuery(sql.toString(), Orders.class, list.toArray());
    }

    private void setValue(StringBuffer sql, Condition condition, ArrayList<Object> list) {
        if (condition.getWid()!=null && !condition.getWid().isEmpty()){
            sql.append(" AND id=?");
            list.add(condition.getWid());
        }else if (condition.getUsername()!=null && !condition.getUsername().isEmpty()){
            sql.append(" AND usernameby=?");
            list.add(condition.getUsername());
        }else if (condition.getwType()!=null){
            sql.append(" AND w_type=?");
            list.add(condition.getwType());
        }else if (condition.getWdate()!=null){
            sql.append(" AND ordertime>?");
            list.add(condition.getWdate());
        }
    }
/*
    public static void main(String[] args) {
        new OrdersDaoImpl().queryAll();
    }

*/
}
